%% Author : lichuang 
-module(echubby_config).
-export([parse_file/1,
	 get_item/1,
	 get_my_server_info/0,
	 get_other_server_info/0]).

-include("echubby.hrl").

parse_file(File) ->
  ets:new(?ECHUBBY_CONFIG, [set, named_table]),
  case file:consult(File) of
    {ok, Terms} ->
      lists:map(fun process_term/1, Terms),
      {ok};
    {error, Reason} ->
      ?ERROR_MSG("consult file error: ~p", [Reason]),
      {error}
  end.

get_item(Item) ->
  [{_, Value}] = ets:lookup(?ECHUBBY_CONFIG, Item),
  Value.

get_my_server_info() ->
  MyServerId = get_item(my_server_id),
  ServerInfo = get_item(server_info),
  [{Id, Host, Port} || {Id, Host, Port} <- ServerInfo, Id =:= MyServerId].

get_other_server_info() ->
  MyServerId = get_item(my_server_id),
  ServerInfo = get_item(server_info),
  [{Id, Host, Port} || {Id, Host, Port} <- ServerInfo, Id =/= MyServerId].

process_term(Term) ->
  case Term of
    {my_server_id, Id}     ->
      store_config(my_server_id, Id);
    {leader_port, LeaderPort}     ->
      store_config(leader_port, LeaderPort);
    {accept_client_port, AcceptClientPort}     ->
      store_config(accept_client_port, AcceptClientPort);
    {server_info, ServerInfo}     ->
      store_config(server_info, ServerInfo)
  end.

store_config(Item, Value) ->
  ets:insert(?ECHUBBY_CONFIG, {Item, Value}).
